package com.szzg10.oracle.chapter38;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.jdbc.pool.OracleDataSource;

public class JdbcCircle {

	public static void main(String[] args) throws SQLException {
		
		System.out.println("Please enter information for connection");
		String user;
		String password;
		String database;
		
		user = readEntry("user: ");
		int slash_index = user.indexOf('/');
		if(slash_index != -1) {
			password = user.substring(slash_index + 1);
			user = user.substring(0, slash_index);
		}
		else {
			password = readEntry("password: ");
		}
		
		database = readEntry("database (a TNSNAME entry): ");
		System.out.println("Connecting to the databse...");
		
		OracleDataSource oracleDataSource = new OracleDataSource();
		oracleDataSource.setURL("jdbc:oracle:oci8:" + user + "/" + password + "@" + database);
		System.out.flush();
		
		Connection connection = oracleDataSource.getConnection();
		System.out.println("Connected.");
		
		Statement statement = connection.createStatement();
		
		ResultSet resultSet = statement.executeQuery("select Radius from RADIUS_VALS");
		while(resultSet.next()) {
			int radInput = resultSet.getInt("RADIUS");
			double result = area(radInput);
			
			String sql = "insert into AREAS values(" + radInput + ", " + result + ")";
			
			Statement insArea = connection.createStatement();
			insArea.execute(sql);
		}
		
		resultSet.close();
		statement.close();
		connection.close();
	}
	
	public static double area(int rad) {
		double pi = 3.1415927;
		double areacircle = pi * rad * rad;
		
		return areacircle;
	}
	
	static String readEntry(String prompt) {
		try {
			StringBuffer buffer = new StringBuffer();
			System.out.print(prompt);
			System.out.flush();
			
			int c = System.in.read();
			while(c != '\n' && c != -1) {
				buffer.append((char)c);
				c = System.in.read();
			}
			
			return buffer.toString().trim();
		}
		catch(IOException e) {
			return "";
		}
	}
}
